# Contributor: Will Sinatra <wpsinatra@gmail.com>
# Maintainer: Will Sinatra <wpsinatra@gmail.com>
pkgname=fennel
pkgver=1.1.0
pkgrel=1
pkgdesc="A Lua Lisp Language"
url="https://fennel-lang.org"
arch="all" #detects noarch, but contains compiled binaries
license="MIT"
options="net"
source="fennel-$pkgver.tar.gz::https://git.sr.ht/~technomancy/fennel/archive/$pkgver.tar.gz"
replaces="fennel"

_lua_versions="5.2 5.3 5.4"
for _v in $_lua_versions; do
	makedepends="$makedepends lua$_v lua$_v-dev lua$_v-libs"
	subpackages="$subpackages $pkgname$_v:_subpackage $pkgname$_v-doc:_doc"
done

prepare() {
	default_prepare

	for _v in $_lua_versions; do
		cp -r "$builddir" "$builddir-$_v"
	done
}

build() {
	for _v in $_lua_versions; do
		msg "Building for lua$_v..."
		cd "$builddir-$_v"

		make fennel.lua \
			 COMPILE_ARGS="FENNEL_PATH=src/?.fnl FENNEL_MACRO_PATH=src/?.fnl CC_OPTS=" \
			 fennel-bin \
			 LUA=lua$_v \
			 NATIVE_LUA_LIB=/usr/lib/lua$_v/liblua.so \
			 BIN_LUA_VERSION=$_v \
			 LUA_INCLUDE_DIR=/usr/include/lua$_v \
			 BIN_LUA_DIR=/usr/bin/lua$_v

		./fennel-bin --compile src/fennel/binary.fnl > binary.lua
	done
}

check() {
	for _v in $_lua_versions; do
		msg "Testing for lua$_v..."
		cd "$builddir-$_v"

		make test LUA=lua$_v
	done
}

package() {
	mkdir -p "$pkgdir"
}

_subpackage() {
	local _v="${subpkgname#"$pkgname"}"
	pkgdesc="A Lua Lisp Language for Lua $_v"
	install_if="lua$_v $pkgname=$pkgver-r$pkgrel"
	depends="$depends lua$_v"

	cd "$builddir-$_v"

	install -Dm0644 "fennel.lua" \
			-t "$subpkgdir/usr/share/lua/$_v/"

	install -Dm0644 "binary.lua" \
			-t "$subpkgdir/usr/share/lua/$_v/fennel/"

	install -Dm0755 "fennel-bin" \
			"$subpkgdir/usr/bin/fennel$_v"
}

_doc() {
	local _ver=${subpkgname#"$pkgname"}
	local _v=$(printf '%s' "$_ver" | sed 's|-doc||')
	pkgdesc="Documentation for Fennel built with Lua$_v"

	cd "$builddir-$_v"

	gzip -9 fennel.1
	install -Dm0644 "fennel.1.gz" \
			-t "$subpkgdir/usr/share/man/man1/"
}

sha512sums="
86e92e399118a3aff8d49098b1a914bca6fdcd898aabcdfda38803a2e69a1d179bd972edece500ce2d912a895d15b8aaf1b05c8840e0062cf6d4043b862457b3  fennel-1.1.0.tar.gz
"
